package learn.up.java.md;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;
import org.junit.Test;

public class HMAC {
	
	private static String str = "pass";

	@Test
	public void test() {
		try {
			KeyGenerator generator = KeyGenerator.getInstance("HmacMD5");
			SecretKey key = generator.generateKey();//产生密钥
			//获得密钥
			byte[] data = key.getEncoded();
			//还原密钥
			SecretKey restoreKey  = new SecretKeySpec(data, "HmacMD5");
			//获取MAC实例
			Mac mac = Mac.getInstance(restoreKey.getAlgorithm());
			//初始化
			mac.init(restoreKey); 
			//执行摘要
			byte[] doFinal = mac.doFinal(str.getBytes());
			String hexString = Hex.encodeHexString(doFinal);
			System.out.println("Hmac带key的摘要"+hexString);
			
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		}
	}
	
}
